﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using Aandelendelen.Mail;
using Aandelendelen.Db;
using Aandelendelen.Obs;

namespace Aandelendelen.Admin
{
	public partial class AdminChangeBalance : AdminBaseForm
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			ClientScriptManager cs = Page.ClientScript;
			cs.RegisterOnSubmitStatement(this.GetType(), "onsubmit", "return ValidateAdminChangeBalance('" + this.tbAmount.TextBox.ClientID + "');");

			if (!this.IsPostBack)
			{
				this.LoadDropDown();
				string uid = this.Request["uid"];
				if (string.IsNullOrEmpty(uid) == false)
					this.tbUserId.Text = uid;
			}
			else
			{
				this.HandleChange();
			}
		}

		private void HandleChange()
		{
			string uid = this.tbUserId.Text.ToLower();

			Query query = new Query("s_getemail", "Gebruikersnaam", uid, OleDbType.Char);

			ResultSet resultSet = (ResultSet)query.Execute();

			if (resultSet.Count == 0)
			{
				this.lblSuccess.Text = "FAILURE: Userid not found!!";
				this.lblSuccess.ForeColor = System.Drawing.Color.Red;
			}
			else
			{
				this.lblSuccess.Text = "SUCCESS";
				this.lblSuccess.ForeColor = System.Drawing.Color.DarkGreen;

				decimal amount = decimal.Parse(this.tbAmount.TextBox.Text);
				int type = Convert.ToInt32(this.DropDownList1.SelectedValue);
				if (type < 0)
					amount = -amount;

				this.InsertMutation((int)resultSet[0, "Id"], amount, type);

				this.SendConfirmationMail(amount, resultSet);
			}
		}

		private void InsertMutation(int userId, decimal amount, int type)
		{
			CommonQueries.InsertSaldoMutation(userId, amount, type, 0);
		}

		private void SendConfirmationMail(decimal amount, ResultSet resultSet)
		{
			Userinfo userInfo = new Userinfo(resultSet, false);

			MailArguments mailArgs = MailArguments.MailArgs;
			mailArgs.Clear();

			mailArgs["{oldsaldo}"] = ObjectFormatter.GetCurrencyString(userInfo.Saldo - amount);
			mailArgs["{newsaldo}"] = ObjectFormatter.GetCurrencyString(userInfo.Saldo);
			mailArgs["{aanhef}"] = userInfo.MailAanhef;
			mailArgs["{amount}"] = ObjectFormatter.GetCurrencyString(amount);
			mailArgs["{reason}"] = this.DropDownList1.SelectedItem.Text.ToLower();
			mailArgs["{username}"] = userInfo.Gebruikersnaam;

			EMail email = MailCache.GetMail("balancechanged");
			email.Recipients = userInfo.Email;

			email.QueueSingle();
		}

		private void LoadDropDown()
		{
			MutationDescription description = MutationDescription.GetInstance();

			foreach (string key in description.Keys)
			{
				this.DropDownList1.Items.Add(new ListItem(description[key], key));
			}
		}
	}
}